package cn.schoolwow.util.module.query.jsonobject.service;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.module.query.jsonobject.domain.JSONObjectQueryOption;

import java.util.Collection;

public class GetJSONObjectFieldsValueFlow implements BusinessFlow {
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        getSingleFieldValue(flowContext);
        getMultipleFieldValue(flowContext);
    }

    public String name() {
        return "通过反射获取实例指定字段列表的值";
    }

    private void getSingleFieldValue(FlowContext flowContext){
        JSONObjectQueryOption jsonObjectQueryOption = (JSONObjectQueryOption) flowContext.checkData("jsonObjectQueryOption");
        Collection<String> fieldNames = (Collection<String>) flowContext.checkData("fieldNames");

        if(fieldNames.size()==1){
            String fieldName = fieldNames.iterator().next();
            if(!jsonObjectQueryOption.object.containsKey(fieldName)){
                throw new IllegalArgumentException("JSON字段不存在!字段名:"+fieldName);
            }
            Object fieldValue = jsonObjectQueryOption.object.get(fieldName);
            flowContext.putReturnData("fieldValue", fieldValue);
            flowContext.brokenCurrentFlow("获取单个属性的值");
        }
    }

    private void getMultipleFieldValue(FlowContext flowContext){
        JSONObjectQueryOption jsonObjectQueryOption = (JSONObjectQueryOption) flowContext.checkData("jsonObjectQueryOption");
        Collection<String> fieldNames = (Collection<String>) flowContext.checkData("fieldNames");

        if(fieldNames.size()>1){
            StringBuilder builder = new StringBuilder();
            for(String fieldName:fieldNames){
                String fieldValue = jsonObjectQueryOption.object.getString(fieldName);
                builder.append(fieldValue+":");
            }
            builder.deleteCharAt(builder.length()-1);
            flowContext.putReturnData("fieldValue", builder.toString());
        }
    }
}
